//
//  WKWebViewController.swift
//  DemoUI
// WKWebview 的使用 网页浏览
//  Created by 白瑾浩 on 2022/1/8.
//

import UIKit
import WebKit

class WKWebViewController: UIViewController, WKUIDelegate {
    var mWKWebView:WKWebView?
    var processView:UIProgressView?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.title = "WKWebView的使用"
        
        //简单的使用WKWebView
        
        //创建网页配置
        let mWKWebViewConfiguration = WKWebViewConfiguration()
        //配置进程池
        let mWKProcessPool = WKProcessPool()
        mWKWebViewConfiguration.processPool = mWKProcessPool
        
        //偏好配置
        let mWKPreferences = WKPreferences()
        mWKPreferences.minimumFontSize = 0 //设置网页的最小字号
        mWKPreferences.javaScriptEnabled = true //支持javascript
        mWKPreferences.javaScriptCanOpenWindowsAutomatically = true //设置是否允许不经过用户交互由javascript代码自动打开窗口
        mWKWebViewConfiguration.preferences = mWKPreferences
        
        mWKWebView =  WKWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height), configuration: mWKWebViewConfiguration )
        self.view.addSubview( mWKWebView! )
        let url = URL(string: "https://www.baidu.com")
        let request = URLRequest(url: url!)
        mWKWebView!.load( request )
        
        //创建加载进度条
        processView = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 10))
        processView?.progressTintColor = UIColor.green
        processView?.progress = 0
        
        self.view.addSubview( processView! )
        
        //监听进度
        mWKWebView?.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil)
        
        //实现委托回调的函数
        mWKWebView?.uiDelegate = self
        //复杂的使用WKWebView  看书 263页
        
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress"{
            //估计进度
            processView?.progress = Float(mWKWebView!.estimatedProgress)
        }
    }
    
    func webViewDidClose(_ webView: WKWebView) {
        
    }
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
